package ycl.system.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ycl.base.entity.Area;
import ycl.base.req.SysUserReq;
import ycl.common.ApiResult;
import ycl.common.base.service.impl.BaseServiceImpl;
import ycl.common.enums.ApiResultEnum;
import ycl.common.exception.CustomException;
import ycl.common.models.res.IdCardResolve;
import ycl.common.utils.BeanConvertUtil;
import ycl.common.utils.UserUtil;
import ycl.system.entity.SysUser;
import ycl.system.feign.BaseFeign;
import ycl.system.mapper.SysUserMapper;
import ycl.system.req.UserPrefectReq;
import ycl.system.res.SysUserRes;
import ycl.system.service.SysUserService;
import ycl.system.utils.SysUserPrivacyUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author ycl
 * @since 2022-03-03 11:43:57
 */
@Service
public class SysUserServiceImpl
		extends BaseServiceImpl<SysUserMapper, SysUser, SysUserReq, SysUserRes>
		implements SysUserService {

	@Resource
	private SysUserMapper sysUserMapper;
	@Resource
	private BaseFeign baseFeign;


	@Override
	public SysUser getById(Serializable id) {
		SysUser user = sysUserMapper.selectById(id);
		return SysUserPrivacyUtil.hidePrivacy(user);
	}

	@Override
	@Transactional
	public void prefectDetail(HttpServletRequest request, UserPrefectReq req) {
		Long userId = getUserId(request);
		SysUser user = BeanConvertUtil.convert(req, SysUser.class);
		IdCardResolve info = UserUtil.getUserInfoByIdCard(req.getIdCard());
		if (sysUserMapper.selectExistByMobile(req.getMobile()))
			throw new CustomException(ApiResultEnum.CUSTOM_MOBILE_REGISTER);
		ApiResult<Area> result = baseFeign.getAreaByCode(info.getArea());
		if (!result.isSuccess())
			throw new CustomException(ApiResultEnum.CUSTOM_VERIFY_ID_CARD_NOT_PASS);
		user.setId(userId);
		user.setBirthday(info.getBirthday());
		sysUserMapper.updateById(user);
	}
}
